package com.cskaoyan.app.wxservice.impl;

import com.cskaoyan.app.bean.bo.WxCollectBo;
import com.cskaoyan.app.bean.common.CommonData;
import com.cskaoyan.app.bean.po.*;
import com.cskaoyan.app.mapper.*;
import com.cskaoyan.app.wxservice.WxCollectService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author: 廖平安
 * @CreateTime: 2023-01-02  16:22
 * @Description: TODO
 * @Version: 1.0
 */
@Service
public class WxCollectServiceImpl implements WxCollectService {
    @Autowired
    private MarketCollectMapper collectMapper;

    @Override
    public CommonData<WxCollectBo> list(Integer type, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        MarketCollectExample example = new MarketCollectExample();
        example.createCriteria().andDeletedEqualTo(false);
        List<MarketCollect> marketCollects = collectMapper.selectByExample(example);
        List<WxCollectBo> list = new ArrayList<>();
        PageInfo<WxCollectBo> info;
        if (marketCollects.size() != 0) {
            list = collectMapper.selectCollect();
        }
        info = new PageInfo<>(list);
        return CommonData.data(info);
    }

    @Override
    public void addOrDelete(Map map) {
        Integer valueId = (Integer) map.get("valueId");
        int type1 = (int) map.get("type");
        Byte type = (byte) type1;
        Subject subject = SecurityUtils.getSubject();
        Integer userId = (Integer) subject.getSession().getAttribute("userid");

        MarketCollectExample example = new MarketCollectExample();
        MarketCollectExample.Criteria criteria = example.createCriteria();
        criteria.andValueIdEqualTo(valueId);

        List<MarketCollect> marketCollects = collectMapper.selectByExample(example);

        if (marketCollects.size() == 0) {
            MarketCollect collect = new MarketCollect();
            collect.setType(type);
            collect.setValueId(valueId);
            collect.setUserId(userId);
            collect.setAddTime(new Date());
            collect.setUpdateTime(new Date());
            collectMapper.insertSelective(collect);
        } else {
            MarketCollect marketCollect = marketCollects.get(0);
            MarketCollect collect = new MarketCollect();
            if (marketCollect.getDeleted() == true) {
                collect.setDeleted(false);
            } else {
                collect.setDeleted(true);
            }
            collectMapper.updateByExampleSelective(collect, example);
        }
    }
}
